package com.ymy.sample.Dao.Impl;

import com.ymy.sample.Dao.UsersDao;
import com.ymy.sample.Entity.UsersEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ymy.hadoop
 * @date 2019/3/19 上午10:35
 */

@Repository
public class UserDaoImpl implements UsersDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<UsersEntity> usersList() {
        List<UsersEntity> list = jdbcTemplate
                .query("select * from user_manager"
                        ,new Object[]{}
                        ,new BeanPropertyRowMapper(UsersEntity.class));
        return list;
    }

    @Override
    public UsersEntity findUserOne(String name) {
        List<UsersEntity> list = jdbcTemplate
                .query("select * from user_manager where user_name=?"
                        ,new Object[]{name}
                        ,new BeanPropertyRowMapper(UsersEntity.class));
       if (list != null && list.size() > 0){
           UsersEntity usersEntity = list.get(0);
           return usersEntity;
       }else {
           return null;
       }
    }

    @Override
    public void saveUser(UsersEntity usersEntity) {
        jdbcTemplate
                .update("insert" +
                        " into user_manager" +
                        "(user_name, password,telPhone) " +
                        "values(?,?,?)"
                        ,usersEntity.getUserName()
                        ,usersEntity.getPassword()
                        ,usersEntity.getTelPhone());
    }

    @Override
    public void updateUser(UsersEntity usersEntity) {
        jdbcTemplate.update("update user_manager " +
                "set password=?" +
                ",telPhone=?" +
                "where user_name=?"
                ,usersEntity.getPassword()
                ,usersEntity.getTelPhone()
                ,usersEntity.getUserName());

    }

    @Override
    public void removeUser(String name) {
        jdbcTemplate.update("delete from user_manager where user_name=?",
                name);
    }
}
